# -*- coding: utf-8 -*-

from DnsValidator import DnsValidator
from HostsValidator import HostsValidator
from WSResult import WSResult

class DnsFindersResult(WSResult):
	# http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1
	zones = ['com', 'biz', 'info', 'edu', 'gov', 'org', 
			 'aero', 'coop', 'eu', 'int', 'mil', 'museum', 
			 'name', 'net', 'co']
	ip = ''
	
	def __init__(self, ip):
		self.ip = ip
	
	def put(self, host):
		if host.count('.') > 1:
			name = ''
			parts = list(reversed(host.split('.')))
			for part in parts:
				if parts.index(part) == 0:
					name = part
					continue
				elif parts.index(part) == 1:
					name = part + '.' + name
					try:
						self.zones.index(part)
						continue
					except ValueError:
						pass
				else:
					name = part + '.' + name
					
				self.results.append(name) 
		else:
			self.results.append(host)
		
		return self
	
	def result(self):
		for col in ['valids', 'invalids', 'errors']:
			self.results[col] = list(set(self.results[col]))
			self.results[col].sort()
		return self.results
	
	# TODO - DNS из конфига
	def validate_result(self):
		self.unique()
		self.results = DnsValidator('8.8.8.8').validate(self.results, self.ip)
		self.results['hosts valids'] = HostsValidator().validate(self.results['invalids'], self.ip) if len(self.results['invalids']) else []
		return self
			
	def as_string(self):
		result = ""
		
		for col in ['valids', 'invalids', 'errors', 'hosts valids']:
			result += "========= " + col + " ==========\n"
			for s in self.result()[col]:
				result += s + "\n" 
		
		return result

